package com.lzx.httpclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;


public class FileBody extends AbstractBody {
	
	private File file;
	
	private String filename;
	
	private String name;
	
	public FileBody(File file, String name) {
		this.file = file;
		this.name = name;
	}
		

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	
	
//	Content-Disposition: form-data; name="uploadFile"; filename="1.txt" Content-Type: text/plain
	@Override
	public void writeTo(OutputStream os, boolean writeContent) {
		try {
//			-----------------------------98942870323811 
//			Content-Disposition: form-data; name="uploadFile"; filename="a.txt" 
//			Content-Type: text/plain 
//			
//			22222222222222222222
			
			StringBuilder sb = new StringBuilder();
			sb.append("--" + this.boundary + LR);
			sb.append("Content-Disposition: form-data; name=\""+  this.name +"\"; filename=\""+ this.file.getName() +"\"" + LR);
			sb.append("Content-Type: text/plain" + LR);
			sb.append(LR);
			os.write(sb.toString().getBytes());
			System.out.print(sb);
			
			if(writeContent) {
				byte[] b = new byte[1024];
				InputStream is = new FileInputStream(file);
				int i;
				while((i = is.read(b, 0 , b.length)) != -1) {
					os.write(b, 0, i);
					System.out.print(i);
				}
				os.flush();
				
			}
		
			os.write("\r\n".getBytes());
//			os.write("22222222222222222222\r\n".getBytes());
			System.out.println("22222222222222222222");
			
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	@Override
	public long getContentLength() {
		// TODO Auto-generated method stub
		return file.length();
	}
	
	
	
	
	
	
	

}
